package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.param.UserParam;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.api.feign.system.dto.SysUserDTO;
import com.meteor.convert.ComplaintConvert;
import com.meteor.convert.MalfunctionConvert;
import com.meteor.entity.Complaint;
import com.meteor.entity.Malfunction;
import com.meteor.entity.Publicity;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.ComplaintMapper;
import com.meteor.mapper.MalfunctionMapper;
import com.meteor.query.ComplaintQuery;
import com.meteor.query.MalfunctionQuery;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.query.PublicityQuery;
import com.meteor.service.CommunityService;
import com.meteor.service.ComplaintService;
import com.meteor.service.MalfunctionService;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.ComplaintVO;
import com.meteor.vo.MalfunctionVO;
import com.meteor.vo.PublicityVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class MalfunctionServiceImpl extends BaseServiceImpl<MalfunctionMapper, Malfunction> implements MalfunctionService {

    private final SystemFeign systemFeign;

    private final CommunityService communityService;

    @Override
    public void save(MalfunctionVO vo) {
        Malfunction  entity= MalfunctionConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

            /*if(ObjectUtils.isEmpty(vo.getCommunityId())){
                OrgAndCommunityQuery query = new OrgAndCommunityQuery();
                query.setOrgId(vo.getOrgId());
                List<CommunityVO> communityVOS = communityService.orgCommunity(query);
                if(ObjectUtils.isEmpty(communityVOS)){
                    throw new ServerException("该机构下没有小区");
                }
                entity.setCommunityId(communityVOS.get(0).getId());
            }*/

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

        if(!ObjectUtils.isEmpty(vo.getImagesUrl())){
            entity.setUrl(JSON.toJSONString(vo.getImagesUrl()));
        }

        entity.setMalfunctionStatus(0);

        //TODO 处理人


//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(MalfunctionVO malfunctionVO) {
        Malfunction malfunction = MalfunctionConvert.INSTANCE.convert(malfunctionVO);
        if (ObjectUtils.isEmpty(malfunction.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(malfunction);

    }

    @Override
    public MalfunctionVO getMalfunction(String id) {
        return MalfunctionConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<MalfunctionVO> getMalfunctionVOList(MalfunctionQuery query) {
        List<Malfunction> complaints = baseMapper.selectList(getWrapper(query));

        return MalfunctionConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<MalfunctionVO> pageMalfunctionVO(MalfunctionQuery query) {


        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Malfunction> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<MalfunctionVO> list = baseMapper.getList(params);

        Map<String, SysUserDTO> sysUserMap = new HashMap<>();
        List<String> userIds = list.stream().filter(t->!ObjectUtils.isEmpty(t.getDisposeUser())).map(t->t.getDisposeUser()).collect(Collectors.toList());
        if(!ObjectUtils.isEmpty(userIds)){
            UserParam userParam = new UserParam();
            userParam.setUserIds(userIds);
            ResponseData responseData = JSON.parseObject(systemFeign.userList(userParam),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                List<SysUserDTO> sysUserDTOs =  JSON.parseArray(responseData.getData().toString(), SysUserDTO.class);
                sysUserMap = sysUserDTOs.stream().collect(Collectors.toMap(SysUserDTO::getId, t->t));
            }
        }
        Map<String, SysUserDTO> finalSysUserMap = sysUserMap;
        list.forEach(t->{
            if(!ObjectUtils.isEmpty(t.getUrl())){
                t.setImagesUrl(JSON.parseArray(t.getUrl(), String.class));
            }
            if(!ObjectUtils.isEmpty(t.getDisposeUser())&&!ObjectUtils.isEmpty(finalSysUserMap.get(t.getDisposeUser()))){
                t.setDisposeUserName(finalSysUserMap.get(t.getDisposeUser()).getRealName());
            }
        });

        return new PageResult<>(list, page.getTotal());


//        IPage<Malfunction> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<MalfunctionVO>(MalfunctionConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());

    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public List<MalfunctionVO> getUserMalfunction(String userId) {

        List<MalfunctionVO> malfunctionVOS = baseMapper.getUserMalfunction(userId);

        return malfunctionVOS;
    }


    private Map<String, Object> getParams(MalfunctionQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("content", query.getContent());
        params.put("type", query.getType());
        params.put("orgId", query.getOrgId());
        params.put("merchantId", query.getMerchantId());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_malfunction"));

        return params;
    }

    private Wrapper<Malfunction> getWrapper(MalfunctionQuery query){
        LambdaQueryWrapper<Malfunction> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getContent()), Malfunction::getContent, query.getContent());
        wrapper.eq(StrUtil.isNotBlank(query.getMerchantId()), Malfunction::getMerchantId, query.getMerchantId());
        wrapper.eq(StrUtil.isNotBlank(query.getOrgId()), Malfunction::getOrgId, query.getOrgId());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }

}
